require 'digest/sha2'

class Cliente < ActiveRecord::Base
  default_scope :order => 'nombre'
  validates :ci_rif, :presence => true, :uniqueness => true, :numericality => { :only_integer => true }, :length => { :in => 6..8 }
  validates :correo, :presence => true, :uniqueness => true
  validates :telefono, :length => { :in => 10..12 }, :numericality => { :only_integer => true }
  

  validates :password, :confirmation => true
  attr_accessor :password_confirmation
  attr_reader   :password

  validate  :password_must_be_present

  def Cliente.authenticate(correo, password)
    if cliente = find_by_correo(correo)
      if cliente.hashed_password == encrypt_password(password, cliente.salt)
        cliente
      end
    end
  end

  def Cliente.encrypt_password(password, salt)
    Digest::SHA2.hexdigest(password + 'wibble' + salt)
  end
  
  # 'password' is a virtual attribute
  def password=(password)
    @password = password

    if password.present?
      generate_salt
      self.hashed_password = self.class.encrypt_password(password, salt)
    end
  end
 
  after_destroy :ensure_an_admin_remains

  def ensure_an_admin_remains
    if Cliente.count.zero?
      raise 'No se puede eliminar el ultimo usuario'
    end
  end 

  private
    def password_must_be_present
      errors.add(:password, "Indique la clave" ) unless hashed_password.present?
    end
  
    def generate_salt
      self.salt = self.object_id.to_s + rand.to_s
    end
end
